﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using eStock.ChildWindows;
using eStock.Common;
using eStock.Controls;
using eStock.DataObjects;
using eStock.SQL;

namespace eStock
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private UIComponents _wndComponents;
        private UIComponentTypes _wndComponentTypes;

        public static SQLDatabase Database { get; private set; }

        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindowLoaded;
        }

        void MainWindowLoaded(object sender, RoutedEventArgs e)
        {
            BusyIndi.IsBusy = true;
            Threading.RunAsThread(Init);
            Threading.WaitForThreadsAsnc(() => { }, () => Dispatcher.Invoke(new Func<bool>(() => BusyIndi.IsBusy = false)));
        }

        private void SetupDatabase()
        {
            Database.QueryWrite(Properties.Settings.Default.db_local
                                    ? Properties.Resources.sqlite_default
                                    : Properties.Resources.sql_default);
        }

        private void Init(int threadID, object parameter)
        {
            LoadDatabase();

            Dispatcher.Invoke(new Action(() =>
                                        {
                                            //Initialize SubControls
                                            //TODO: Check if parameters are needed
                                            _wndComponents = new UIComponents();
                                            _wndComponentTypes = new UIComponentTypes();

                                            // Invoke a ribbon tabchange
                                            RibbonTabChanged(this,null);

                                        }));
        }


        public void LoadDatabase()
        {
            try
            {
                if (Database == null)
                {
                    if (Properties.Settings.Default.db_local)
                        Database = new Sqlite();
                    else
                        Database = new MySQL();

                    if (!Database.Connect())
                        throw new Exception();
                }
                SetupDatabase();

                //Load Shops
                SQLDataReader res = Database.QueryRead("SELECT * FROM es_addresses ORDER BY id");
                Dictionary<string, object> data = Database.FetchArray(res);
                while (data != null)
                {
                    Address c = new Address
                                    {
                                        Id = Convert.ToInt32(data["id"]),
                                        ImgId = Convert.ToInt32(data["imgId"]),
                                        Description = data["description"].ToString(),
                                        Company = data["company"].ToString(),
                                        Street = data["street"].ToString(),
                                        PLZ = data["PLZ"].ToString(),
                                        Location = data["location"].ToString(),
                                        Country = data["country"].ToString(),
                                        Name = data["name"].ToString(),
                                        Phone = data["phone"].ToString(),
                                        Mobile = data["mobile"].ToString(),
                                        Fax = data["fax"].ToString(),
                                        Mail = data["mail"].ToString(),
                                        Web = data["web"].ToString(),
                                        CustomerId = data["customerId"].ToString(),
                                        Login = data["login"].ToString(),
                                        UsSTID = data["UsSTID"].ToString(),
                                        Bank = data["bank"].ToString(),
                                        Blz = data["BLZ"].ToString(),
                                        Konto = data["konto"].ToString(),
                                        SWIFT = data["SWIFT"].ToString(),
                                        IBAN = data["IBAN"].ToString(),
                                        Comments = data["comments"].ToString(),
                                    };
                    DatabaseObjects.Addresses.Add(c);
                    data = Database.FetchArray(res);
                }

                //Load Categories
                res = Database.QueryRead("SELECT * FROM es_categories ORDER BY id");
                data = Database.FetchArray(res);
                while (data != null)
                {
                    ComponentCategory c = new ComponentCategory
                                              {
                                                  Id = Convert.ToInt32(data["id"]),
                                                  ParentId = Convert.ToInt32(data["parentId"]),
                                                  Title = data["title"].ToString(),
                                                  Description = data["description"].ToString()
                                              };

                    DatabaseObjects.Categories.Add(c);
                    data = Database.FetchArray(res);
                }

                //Load Components
                res = Database.QueryRead("SELECT * FROM es_component ORDER BY id");
                data = Database.FetchArray(res);
                while (data != null)
                {
                    Component c = new Component
                                      {
                                          Id = Convert.ToInt32(data["id"]),
                                          TypeId = Convert.ToInt32(data["typeId"]),
                                          ImgId = Convert.ToInt32(data["imgId"]),
                                          Title = data["title"].ToString(),
                                          Description = data["description"].ToString()
                                      };


                    DatabaseObjects.Components.Add(c);
                    data = Database.FetchArray(res);
                }

                //Load tray
                res = Database.QueryRead("SELECT * FROM es_tray ORDER BY id");
                data = Database.FetchArray(res);
                while (data != null)
                {
                    Tray c = new Tray
                                           {
                                               Id = Convert.ToInt32(data["id"]),
                                               ComponentId = Convert.ToInt32(data["componentId"]),
                                               BoxId = Convert.ToInt32(data["boxId"]),
                                               
                                               Title = data["title"].ToString(),
                                               Amount = Convert.ToInt32(data["amount"]),
                                               Price = Convert.ToDouble(data["price"]),
                                               Condition =
                                                   (ConditionType)
                                                   Enum.Parse(typeof (ConditionType), data["condition"].ToString()),
                                               Description = data["description"].ToString()
                                           };
                    DatabaseObjects.Trays.Add(c);
                    data = Database.FetchArray(res);
                }

                foreach (Tray c in DatabaseObjects.Trays)
                {
                    SQLDataReader rtmp =
                        Database.QueryRead("SELECT * FROM es_trayShops WHERE stockId  = '" + c.Id + "'");
                    Dictionary<string, object> datatmp = Database.FetchArray(rtmp);
                    while (datatmp != null)
                    {
                        c.ShopIds.Add(Convert.ToInt32(datatmp["shopId"]));
                        datatmp = Database.FetchArray(rtmp);
                    }
                }



                //Load ComponentType
                res = Database.QueryRead("SELECT * FROM es_componentType ORDER BY id");
                data = Database.FetchArray(res);
                while (data != null)
                {
                    ComponentType c = new ComponentType
                                          {
                                              Id = Convert.ToInt32(data["id"]),
                                              ImgId = Convert.ToInt32(data["imgId"]),
                                              Title = data["title"].ToString(),
                                              CategoryId = Convert.ToInt32(data["categoryId"]),
                                              SerialNr = data["serialNr"].ToString(),
                                              Pins = Convert.ToInt32(data["Pins"]),
                                              Description = data["description"].ToString(),
                                              Smd = Convert.ToBoolean(data["smd"])

                                          };
                    DatabaseObjects.Types.Add(c);
                    data = Database.FetchArray(res);
                }

                //Load Config
                res = Database.QueryRead("SELECT * FROM es_config");
                data = Database.FetchArray(res);
                while (data != null)
                {
                    DatabaseObjects.Config.Add(data["title"].ToString(), data["value"].ToString());
                    data = Database.FetchArray(res);
                }

                //Load Images
                res = Database.QueryRead("SELECT *,LENGTH(image) AS fileLength FROM es_images ORDER BY id");
                data = Database.FetchArray(res);
                while (data != null)
                {
                    Byte[] rawImg = new byte[res.GetUInt32("fileLength")];
                    res.GetBytes(res.GetOrdinal("image"), 0, rawImg, 0, rawImg.Length);
                    Image img = null;
                    Dispatcher.Invoke(new Action(() => { img = new Image {Source = rawImg.ToImage()}; }));

                    DBImage c = new DBImage
                                    {
                                        Id = Convert.ToInt32(data["id"]),
                                        Title = data["title"].ToString(),
                                        ImgType = data["imgType"].ToString(),
                                        Image = img
                                    };
                    DatabaseObjects.Images.Add(c);
                    data = Database.FetchArray(res);
                }

                //Load Orders
                res = Database.QueryRead("SELECT *, " + Database.DateFormat("orderDate", "%m/%d/%Y") + "AS oDate FROM es_orders ORDER BY id");
                data = Database.FetchArray(res);
                while (data != null)
                {
                    Order c = new Order
                                  {
                                      Id = Convert.ToInt32(data["id"]),
                                      ComponentId = Convert.ToInt32(data["componentId"]),
                                      ProjectId = Convert.ToInt32(data["projectId"]),
                                      Title = data["title"].ToString(),
                                      Amount = Convert.ToInt32(data["amount"]),
                                      Status = Convert.ToInt32(data["status"]),
                                      OrderDate = res.GetDateTime("oDate"),
                                      ShopId = Convert.ToInt32(data["shopId"]),

                                  };
                    DatabaseObjects.Orders.Add(c);
                    data = Database.FetchArray(res);
                }

                //Load Projects
                res = Database.QueryRead("SELECT *, " + Database.DateFormat("created", "%m/%d/%Y") + "AS cDate FROM es_projects ORDER BY id");
                data = Database.FetchArray(res);
                while (data != null)
                {
                    Project c = new Project
                                    {
                                        Id = Convert.ToInt32(data["id"]),
                                        ImgId = Convert.ToInt32(data["imgId"]),
                                        Title = data["title"].ToString(),
                                        Description = data["description"].ToString(),
                                        Created = res.GetDateTime("cDate")
                                    };
                    DatabaseObjects.Projects.Add(c);
                    data = Database.FetchArray(res);
                }
                foreach (Project p in DatabaseObjects.Projects)
                {
                    SQLDataReader rtmp =
                        Database.QueryRead("SELECT * FROM es_projectComponents WHERE projectId = '" + p.Id +
                                        "' ORDER BY id");
                    Dictionary<string, object> datatmp = Database.FetchArray(rtmp);
                    while (datatmp != null)
                    {
                        p.Components.Add(Convert.ToInt32(datatmp["componentId"]), Convert.ToInt32(datatmp["amount"]));
                        datatmp = Database.FetchArray(rtmp);
                    }
                }
                Globals.Instance.DBLoaded = true;
            }
            catch (Exception x)
            {
                Globals.Instance.DBLoaded = false;
                string msg;
                if(x.InnerException != null)
                {
                    msg = x.InnerException.Message;
                    if(x.InnerException.InnerException != null)
                        msg = x.InnerException.InnerException.Message;
                }
                else
                    msg = x.Message;
                if (MessageBox.Show("Fehler beim Laden der Daten aus der Datenbank!\n(" + msg + ")\n\nMöglicherweise ist die Konfiguration nicht korrekt. Wollen Sie diese jetzt prüfen?", "Fehler beim Laden der Datenbank", MessageBoxButton.YesNo, MessageBoxImage.Error) == MessageBoxResult.Yes)
                {
                    Dispatcher.Invoke(new Action(() =>
                                                {
                                                    WndSettings stngsWindow = new WndSettings();
                                                    stngsWindow.ShowDialog();
                                                }));
                }
            }

        }

        public void UpdateUI()
        {
            RibbonTabChanged(this, null);
            if (!(ContentPanel.Content is UIControl)) return;
            ((UIControl)ContentPanel.Content).Update();
        }

        private void UpdateDatabase()
        {
            //TODO
        }

        

    }
}
